package com.ferryc.modules.sys.service.impl;

import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ferryc.commons.service.CommonService;
import com.ferryc.commons.utils.StringUtil;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.modules.sys.entity.SysRole;
import com.ferryc.modules.sys.mapper.ISysRoleMapper;
import com.ferryc.modules.sys.service.ISysRoleService;

/**
 * 
 * 类名: ISysRoleService <br/>
 * 作用： 服务<br/>
 * 方法： <br/>
 * 创建者: Ferry C <br/>
 * 添加时间: 2017年12月02日 08:44:23 <br/>
 * 
 */
@Service
@Transactional(readOnly = true)
public class SysRoleServiceImpl extends CommonService<SysRole> implements ISysRoleService {

	@Autowired
	private ISysRoleMapper sysRoleMapper;

	@Override
	protected void init() {
		super.mapper = sysRoleMapper;
	}

	@Override
	public boolean checkRole(SysRole sysRole) {
		SysRole queryRole = new SysRole();
		queryRole.setStatus(StringUtil.EMPTY);
		queryRole.setDelFlag(GlobalConstant.DEL_FLAG_NORMAL);
		queryRole.setRole(sysRole.getRole());
		List<SysRole> list = sysRoleMapper.listByEntity(queryRole);
		if (CollectionUtils.isEmpty(list)) {
			return Boolean.TRUE;
		}
		if (StringUtil.isBlank(sysRole.getId())) {
			return Boolean.FALSE;
		} else {
			if (list.size() == 1 && list.get(0).getId().equals(sysRole.getId())) {
				return Boolean.TRUE;
			}
			return Boolean.FALSE;
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void insertRole(SysRole sysRole) {
		sysRoleMapper.insert(sysRole);
		insertRolePrem(sysRole);
	}

	@Override
	@Transactional(readOnly = false)
	public void updateRole(SysRole sysRole) {
		sysRoleMapper.update(sysRole);
		sysRoleMapper.deletePermissionsRole(sysRole);
		insertRolePrem(sysRole);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteRole(SysRole sysRole) {
		sysRoleMapper.update(sysRole);
		sysRoleMapper.deletePermissionsRole(sysRole);
	}

	@Transactional(readOnly = false)
	private void insertRolePrem(SysRole sysRole) {
		String permissionIds = sysRole.getPermissionIds();
		String[] pArr = permissionIds.split(",");
		for (int i = 0; i < pArr.length; i++) {
			SysRole rolePerm = new SysRole();
			rolePerm.setRoleId(sysRole.getId());
			rolePerm.setPermissionId(pArr[i]);
			sysRoleMapper.insertPermissionsRole(rolePerm);
		}

	}

	@Override
	public List<SysRole> selectRolePermList(String roleId) {
		return sysRoleMapper.selectRolePermList(roleId);
	}

	@Override
	public boolean checkUsePermission(String permissionId) {
		int result = sysRoleMapper.selectPermUseCount(permissionId);
		if (result > 0) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@Override
	public List<String> getPermByRole(String role) {
		return sysRoleMapper.getPermByRole(role);
	}

}